package com.vueblog.webapi.controller.admin;


import com.vueblog.webapi.controller.BaseController;
import com.vueblog.webapi.exception.BusinessException;
import com.vueblog.webapi.request.BasePageRequest;
import com.vueblog.webapi.request.CreateOrUpdateTagRequest;
import com.vueblog.webapi.response.BasePageResponse;
import com.vueblog.webapi.response.BaseResponse;
import com.vueblog.webapi.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author luosj
 * @since 2021-05-15
 */
@Controller
@CrossOrigin
@RequestMapping("/admin/tags")
public class TagController extends BaseController {

    @Autowired
    private ITagService tagService;

    /**
     * 标签管理页面
     */
    @GetMapping("/index")
    public String tagsIndexPage() {
        return "admin/tags";
    }

    /**
     * 分页查询标签
     */
    @PostMapping("/list")
    @ResponseBody
    public BasePageResponse getTagPageList(@RequestBody @Valid BasePageRequest request, BindingResult bindingResult) {
        checkBindingResult(bindingResult);
        return tagService.getTagPageList(request);
    }

    /**
     * 标签列表（下拉框模式）
     */
    @GetMapping("/list")
    @ResponseBody
    public BaseResponse getTagList() {
        return tagService.getTagList();
    }

    /**
     * 创建标签
     */
    @PostMapping("/create")
    @ResponseBody
    public BaseResponse createTag(@RequestBody @Valid CreateOrUpdateTagRequest request, BindingResult bindingResult) throws IllegalAccessException {
        checkBindingResult(bindingResult);
        try {
            return tagService.createTag(request);
        } catch (BusinessException e) {
            return new BaseResponse(-1, e.getMsg());
        }
    }

    /**
     * 编辑标签
     */
    @PutMapping("/update/{id}")
    @ResponseBody
    public BaseResponse updateTagInfo(@RequestBody @Valid CreateOrUpdateTagRequest request, BindingResult bindingResult, @PathVariable("id") String id) {
        checkBindingResult(bindingResult);
        try {
            return tagService.updateTagInfo(request, id);
        } catch (BusinessException e) {
            return new BaseResponse(-1, e.getMsg());
        }
    }

    /**
     * 删除标签
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public BaseResponse deleteTagInfo(@PathVariable("id") String id) {
        return tagService.deleteTagInfo(id);
    }

    /**
     * 根据博客查询标签
     */
    @GetMapping("/byBlog/{id}")
    @ResponseBody
    public BaseResponse getTagByBlog(@PathVariable("id") String id) {
        return tagService.getTagByBlog(id);
    }
}
